/**
 * 
 */
package com.fenoco.filter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import co.com.fenoco.encuentas.persistencia.Usuario;

/**
 * @author Camilo Forero
 * 
 */
public class SecurityFilter implements Filter {
	private static final String URL_ERROR = "/usuario_no_autenticado.jsf";
	private static final ArrayList<String> excepciones = new ArrayList<String>();
	static {
		excepciones.add("/a4j/");
		excepciones.add("/css/");
		excepciones.add("/img/");
		excepciones.add("/login.jsf");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest
				&& response instanceof HttpServletResponse) {

			HttpServletRequest httpRequest = (HttpServletRequest) request;
			if (validarUsuario(httpRequest)) {
				Usuario usuario = (Usuario) httpRequest.getSession()
						.getAttribute("usuario");
				if (usuario != null) {
					chain.doFilter(request, response);
				} else {
					RequestDispatcher dispatcher = request
							.getRequestDispatcher(URL_ERROR);
					dispatcher.forward(request, response);
				}
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}

	}

	private boolean validarUsuario(HttpServletRequest httpRequest) {
		boolean retorno = true;
		String uri = httpRequest.getRequestURI();
		int N = excepciones.size();
		String temp = null;
		for (int i = 0; i < N && retorno; i++) {
			temp = excepciones.get(i);
			retorno = !uri.contains(temp);
		}

		return retorno;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
